package trss.webapp.repository;

import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import trss.model.Torrent;

/**
 *
 * @author Igor Khoroshev
 */
@Repository
public class TorrentRepository {

    private EntityManager entityManager;

    @PersistenceContext
    void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @Transactional
    public void delete(Long id) {
        final Torrent forDelete = entityManager.getReference(Torrent.class, id);
        entityManager.remove(forDelete);
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @Transactional
    public Torrent save(Torrent person) {
        return entityManager.merge(person);
    }

    public int countAll() {
        return ((Integer) entityManager.createQuery("SELECT count(o) from Torrent o").getSingleResult()).intValue();
    }

    @RolesAllowed(value = {"ROLE_USER"})
    public List<Torrent> findAll(int firstResult, int maxResult) {
        return entityManager.createQuery("SELECT o from Torrent o").setFirstResult(firstResult).setMaxResults(maxResult).getResultList();
    }

    @RolesAllowed(value = {"ROLE_USER"})
    public Torrent findById(Long id) {
        return entityManager.find(Torrent.class, id);
    }
    
}
